<template>
  <el-cascader :props="props" @change="change" ref="cascader" />
</template>

<script lang="ts" setup>
import type { CascaderProps, CascaderValue } from "element-plus";
import { getProvincesApi, getCitiesApi, getAreasApi } from "@/api/mock/area";
import { ref } from "vue";
// 对省市区信息进行存储
const ProvinceStr = ref<string>("");
const CityStr = ref<string>("");
const AreaStr = ref<string>("");
// 自定义事件 将用户地址发送给地图组件
const emits = defineEmits(["sendUserAddress"]);
const cascader = ref()

// 进行三级列表的选择后触发，更改category3Id的值
const change = async (val: CascaderValue) => {
  if (Array.isArray(val) && val.length > 0) {
    // 获取当前选择的省市区   eg:['河北省', '石家庄市', '长安区']
    ProvinceStr.value = cascader.value.getCheckedNodes()[0].pathLabels[0];
    CityStr.value = cascader.value.getCheckedNodes()[0].pathLabels[1];
    AreaStr.value = cascader.value.getCheckedNodes()[0].pathLabels[2];
    // console.log(ProvinceStr.value, CityStr.value, AreaStr.value);

    // 用户点击三级地址后发送给地图组件
    emits("sendUserAddress", [ProvinceStr.value, CityStr.value, AreaStr.value]);
  }
};
const props: CascaderProps = {
  lazy: true,
  async lazyLoad(
    node: { level: any; value: any },
    resolve: (arg0: any) => void
  ) {
    const { level, value } = node;
    // level 为级联选择器的层级，值为0或1或……等等。
    // value 为选择的id值
    if (level === 0) { // 初始进入执行 => 用于显示一级列表
      const arr = await getProvincesApi();
      const nodes = arr.map(
        (item: { province: any; name: any; code: any }) => ({
          value: item.province,
          label: item.name,
          code: item.code,
        })
      );
      resolve(nodes);
    } else if (level === 1) { // 选择一级项后, 进入执行 => 用于显示二级列表
      const arr = await getCitiesApi(value as string);
      const nodes = arr.map(
        (item: { province: string; city: string; name: any; code: any }) => ({
          value: item.province + "&city=" + item.city,
          label: item.name,
          code: item.code,
        })
      );
      resolve(nodes);
    } else if (level === 2) { // 选择二级项后, 进入执行 => 用于显示三级列表
      const arr = await getAreasApi(value as string);
      const nodes = arr.map((item: { area: any; name: any; code: any }) => ({
        value: item.area,
        label: item.name,
        code: item.code,
        leaf: level >= 2,
      }));
      resolve(nodes);
    }
  },
};
</script>
<script lang="ts">
export default {
  name: "UserCascader",
};
</script>
